/**** ver 1.0.5 ****/
/* 
--更新记录
---ver 1.0.5
    layer.msg方法增加时间控制参数,默认为1.5
---ver 1.0.4
    埋点统计方法更改,提交时携带更多用户信息参数
    增加方法getAdspaceUrl_signin,客户端协议积分乐园签到标识
---ver 1.0.3
    loading动画点击遮罩时不再会关闭
---ver 1.0.2
    将Statistics方法变更为_CZWeb的方法,优化入参默认值.
    isPhone方法的判断兼容数字类型
    addCookie方法失效时间设置无效的bug
---ver 1.0.1
    增加方法 windows.AJAX 方便统一配置ajax请求
    增加埋点统计方法 windows.Statistics
---ver 1.0.0
    定义全局变量,减少全局变量的污染,变量名_CZWeb;
    增加分享协议getAdspaceUrl_share(brandid,channel,url,name,text,imageUrl);
    增加常用弹窗关闭事件,绑定弹窗内.close类默认为关闭自身弹窗;
    设置了版本号,方便版本控制;
*/
'use strict';

//客户端支付成功后返回 code 为0成功 -1不成功
var clientCallback = function(code,fname,data){
    try{
        var fn = eval(fname);
        if(typeof fn === "function"){
            fn(code,data);
        }
    }catch(e){
        
    }
};
//客户端界面重新显示触发事件
var onResume = function(){};
//客户端界面隐藏触发事件
var onPause = function(){};


//统一ajax接口，方便统一处理。
var AJAX = function(p){
    var def = {"url":"","dataType":"json","type":"POST","data":"","cache":false};
    var opt = $.extend({}, def,typeof p =="string"?{"url":p}:p);
    if(!opt.url){console.log('请求地址为空!');return;}
    $.ajax({
        url : opt.url,
        dataType : opt.dataType,
        type : opt.type,
        cache : opt.cache,
        data: opt.data,
        beforeSend:function(){
            if(typeof(opt.beforSend)=='function'){
                return opt.beforSend();
            }
        },
        success: function(d){
            if(typeof(opt.success)=='function'){
                opt.success(d);
            }
        },
        error: function(e){
            if(typeof(opt.error)=='function'){
                opt.error(e);
            }
        }
    });
};

var _CZWeb = {
    v : "1.0.5"
    //客户端特殊协议头
    ,adspaceArr : {
        "3g":"threegadspace",
        "4g":"fourgadspace"
    }
    //埋点接口
    ,statistics_url: "http://events.keepc.com/operate/statistics2"
    //添加Cookie
    ,addCookie : function(name,value,expiresHours){
        if(!name){
            return;
        }
        var cookieString=name+"="+escape(value); 
        //判断是否设置过期时间 单位小时
        if(expiresHours>0){ 
            var date=new Date(); 
            date.setTime(date.getTime()+expiresHours*3600*1000); 
            cookieString=cookieString+"; expires="+date.toGMTString(); 
        } 
        document.cookie=cookieString; 
    }
    //获取Cookie
    ,getCookie : function(name){ 
        var strCookie=document.cookie; 
        var arrCookie=strCookie.split("; ");
        var cookies = {};
        for(var i=0;i<arrCookie.length;i++){ 
            var arr=arrCookie[i].split("="); 
            if(name){
                if(arr[0]==name)
                    return arr[1]; 
            }else{
                cookies[arr[0]+''] = arr[1];
            }
        }
        return name?"":cookies; 
    }
    //删除Cookie
    ,deleteCookie : function(name){ 
        if(!name){
            return;
        }
        var date=new Date(); 
        date.setTime(date.getTime()-10000); 
        document.cookie=name+"=v; expires="+date.toGMTString(); 
    }
    ,getUrlParams: function(name) {
        var args = new Object();
        var query = location.search.substring(1);
        var pairs = query.split("&");
        for (var i = 0; i < pairs.length; i++) {
            var pos = pairs[i].indexOf('=');
            if (pos == -1) continue;
            var argname = pairs[i].substring(0, pos);
            var value = pairs[i].substring(pos + 1);
            args[argname] = decodeURI(value);
        }
        return name ? (Object.keys(args).length > 0 ? args[name] : "") : args;
    }
    //统计埋点
    ,Statistics : function(data){
        /*
        `cur_url`       '请求的当前页面url',
        `pos_tap`       '点击位置',
        `goto_url`      '跳转url',
        `title_desc`    '标题栏',
        `url_params`    '请求的当前页面额外参数'
        ip   客户端ip
        */
        var href = window.location.href;
        var params = this.getUrlParams();
        var def = {
            cur_url:href.substring(0,href.indexOf('?')>=0?href.indexOf('?'):href.length)
            ,url_param:$.param(this.fromatUrlParam(params))
            ,goto_url:''
            ,title_desc:''
            ,ip:''
        };
        $.get(this.statistics_url, $.extend({},def,params,data));
    }
    ,fromatUrlParam : function(paramArr){
        var p = $.extend(true,{}, paramArr);
        delete p.brandid;
        delete p.bid;
        delete p.pwd;
        delete p.phone;
        delete p.uid;
        delete p.v;
        delete p.pv;
        delete p.sdk;
        delete p.screenw;
        delete p.screenh;
        return p;
    },
    getAdspace:function(brandid){
        return (this.adspaceArr && this.adspaceArr[brandid] || ((brandid||'kc')+"adspace"));
    },
    getAdspaceUrl: function(brandid,url,title,pullrefresh,callback,rightName){
        return this.getAdspace(brandid) + '://wap?param={"page":"","url":"'+ encodeURI(url||'') +'","title":"'+(title||'')+'"'+ (rightName?(',"rightName":"'+rightName+'"'):'') + (callback?(',"callback":"'+callback+'"'):'') + ((typeof pullrefresh =="boolean"&&!pullrefresh)?',"pullrefresh":"false"':'')+'}';
    },
    getAdspaceUrl_web: function(brandid,url){
        return this.getAdspace(brandid) + '://web?param={"page":"","url":"'+ (url||'') +'"}';
    },
    getAdspaceUrl_inline: function(brandid,page){
        return this.getAdspace(brandid) + '://inline?param={"page":"'+page+'","url":"","title":""}';
    },
    getAdspaceUrl_business: function(brandid,goodsid,goodsprice,goodsname,goodsdes,paytype,callback){
        return this.getAdspace(brandid) + '://business?param={"type":"rechargetype","goodsid":"'+(goodsid||'')+'","goodsvalue":"'+(goodsprice||'')+'","goodsname":"'+(goodsname||'')+'","goodsdes":"'+(goodsdes||'')+'","callback":"'+(callback?callback:'')+'", "callbacktype":""'+ (paytype?(',"action":"pay","paytype":"'+paytype+'"'):'')+',"showPayMsg":false}';
    },
    getAdspaceUrl_share: function(brandid,channel,url,name,text,imageUrl){
        return this.getAdspace(brandid) + '://business?param={"type":"share","share_url":"'+(url||'')+'","share_name":"'+(name||'')+'","share_text":"'+(text||'')+'","share_imageUrl":"'+(imageUrl||'')+'","channel":"'+(channel||'')+'","callback":"", "callbacktype":""}';
    },
    getAdspaceUrl_signin: function(brandid){
        return this.getAdspace(brandid) + '://business?param={"type":"signin"}';
    },
    getAdspaceUrl_finish: function(brandid,url,title){
        return this.getAdspace(brandid) + '://finish?param={"page":"","url":"'+encodeURI(url||'')+'","title":"'+(title||'')+'"}';
    },
    getAdspaceUrl_sdk: function(brandid,action,packageName,url){
        return this.getAdspace(brandid) + '://sdk?param={"action":"'+(action||'')+'","package":"'+(packageName||'')+'","url":"'+encodeURI(url||'')+'"}';
    },
    getAdspaceUrl_photo: function(brandid,fn,number){
        return this.getAdspace(brandid) + '://photo?param={"callback":"'+(fn||'')+'","photoNum":"'+(number||'')+'"}';
    },
    isPhone: function(phone){
        return !!(phone+'').match(/^1[3|4|5|7|8][0-9]{9}$/);
    },
    isIDCard: function(code){
        var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
        var tip = "";
        var pass= true;
        if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
            //身份证号格式错误
            pass = false;
        }else if(!city[code.substr(0,2)]){
            //地址编码错误"
            pass = false;
        }else{
            //18位身份证需要验证最后一位校验位
            if(code.length == 18){
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
                //校验位
                var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++)
                {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if(parity[sum % 11] != code[17]){
                    //校验位错误
                    pass =false;
                }
            }
        }
        return pass;
    },
    isAndroid: navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1,
    isIOS: !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
    isWeixin: navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger" || (navigator.userAgent.toLowerCase().indexOf("qq") != -1 && navigator.userAgent.toLowerCase().indexOf("mqqbrowser") == -1 && navigator.userAgent.toLowerCase().indexOf("qqbrowser") == -1),
    imgReady:(function () {
        /*
        *使用案例：
        imgReady('http://logo_cn.png', function () {
            alert('size ready: width=' + this.width + '; height=' + this.height);
        });
        */
        var list = [], intervalId = null,
        // 用来执行队列
        tick = function () {
            var i = 0;
            for (; i < list.length; i++) {
                list[i].end ? list.splice(i--, 1) : list[i]();
            };
            !list.length && stop();
        },
        // 停止所有定时器队列
        stop = function () {
            clearInterval(intervalId);
            intervalId = null;
        };
        return function (url, ready, load, error) {
            var onready, width, height, newWidth, newHeight,
            img = new Image();
            img.src = url;
            // 如果图片被缓存，则直接返回缓存数据
            if (img.complete) {
                ready.call(img);
                load && load.call(img);
                return;
            };
            width = img.width;
            height = img.height;
            // 加载错误后的事件
            img.onerror = function () {
                error && error.call(img);
                onready.end = true;
                img = img.onload = img.onerror = null;
            };
            // 图片尺寸就绪
            onready = function () {
                newWidth = img.width;
                newHeight = img.height;
                if (newWidth !== width || newHeight !== height || newWidth * newHeight > 1024) {
                    ready.call(img);
                    onready.end = true;
                };
            };
            onready();
            // 完全加载完毕的事件
            img.onload = function () {
                // onload在定时器时间差范围内可能比onready快
                // 这里进行检查并保证onready优先执行
                !onready.end && onready();
                load && load.call(img);
                // IE gif动画会循环执行onload，置空onload即可
                img = img.onload = img.onerror = null;
            };
            // 加入队列中定期执行
            if (!onready.end) {
                list.push(onready);
                // 无论何时只允许出现一个定时器，减少浏览器性能损耗
                if (intervalId === null) intervalId = setInterval(tick, 40);
            };
        };
    })()
};

if (typeof layer === 'object') {
    //提示消息
    layer.msg = function(msg,time) {
        return layer.open({
            content: msg,
            skin: 'msg',
            time: time||1.5
        });
    };
    
    //加载
    layer.loading = function(msg,id){
        return layer.open({type: 2,content: msg?(id?('<div id="'+id+'">'+msg+'</div>'):msg):'',shadeClose:false});
    };
    
    //页面
    layer.page = function(html,style){
        return layer.open({
          type: 1
          ,shade: false
          ,content: html
          ,anim: 'up'
          ,style: 'width:100%; margin:0 auto; height:100%; border: none; -webkit-animation-duration: .5s; animation-duration: .5s;'+(style||'')
        });
    };
    
    //自定义弹窗
    layer.dialog = function(html,close){
        var opt = {type:1,content:html,style:'background-color:rgba(0,0,0,0);',shade:true,shadeClose:false,end:function(){console.log('销毁了')}};
        if(typeof close === "function"){
            opt.end = close;
        }
        return layer.open(opt);
    };

    //底部对话框
    layer.footer = function(msg,buttons,callback_yes){
        return layer.open({
            content: msg
            ,btn: buttons
            ,skin: 'footer'
            ,yes: function(index){
              if(typeof callback_yes === "function"){
                callback_yes(index);
              }else{
                layer.close(index);
              }
            }
        });
    }

    //确认框
    layer.confirm = function(msg,buttons,callback_yes){
        return layer.open({
            content: msg
            ,btn: buttons
            ,yes: function(index){
              if(typeof callback_yes === "function"){
                callback_yes(index);
              }else{
                layer.close(index);
              }
            }
        });
    };

    //绑定关闭按钮事件
    document.addEventListener("click",function(e){
        var _this = e.target;
        if(_this.classList.contains('close')){
            while(!_this.classList.contains('layui-m-layer')){
                _this=_this.parentNode;
                if(_this==null)
                    return;
            }
            var index = _this.attributes.index.value;
            layer.close(index);
        }
    },false);
}
